package com.wangjiacai.utils.web.service.impl;

import com.wangjiacai.utils.web.service.AsyncService;
import org.springframework.stereotype.Service;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@Service
public class AsyncServiceImpl implements AsyncService {

    @Override
    public <T> T call(Callable<T> callable) {
        CompletableFuture<T> future= CompletableFuture.supplyAsync(() -> {
            try {
                return callable.call();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        });
        future.join();
        return future.getNow(null);
    }

    @Override
    public <T> T call(Callable<T> callable, Executor executor) {
        CompletableFuture<T> future= CompletableFuture.supplyAsync(() -> {
            try {
                return callable.call();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        },executor);
        future.join();
        return future.getNow(null);
    }

    @Override
    public void run(Runnable runnable) {
        CompletableFuture.runAsync(() -> runnable.run());
    }

    @Override
    public void run(Runnable runnable, Executor executor) {
        CompletableFuture.runAsync(() -> runnable.run(),executor);
    }

}
